package com.javaxiaobang.pachong.file;

import com.alibaba.fastjson.util.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Description : http文件图片下载
 * @Author : qtian
 * @Date: 2020-06-16 16:22
 */
public class FileTest {

    public static void main(String[] args) throws Exception {
        String urlString = "https://gjscrm-1256038144.cos.ap-beijing.myqcloud.com/clerkQrCodeUrl/445777166120001.jpg";
        String filename = "/xiaobang/tmp/" + File.separator + "test中文(*´▽｀)ノノ测试.jpg";  //下载路径及下载图片名称
        download(urlString, filename);
    }

    public static void download(String urlString, String fileName) {
        InputStream is = null;
        FileOutputStream os = null;
        try {
            // 构造URL
            URL url = new URL(urlString);
            // 打开连接
            URLConnection con = url.openConnection();
            con.setConnectTimeout(500);
            con.setReadTimeout(500);
             // 输入流
            is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File file = new File(fileName);
            os = new FileOutputStream(file, true);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.flush();
        } catch (Exception e) {

        }finally {
            // 完毕，关闭所有链接
            IOUtils.close(os);
            IOUtils.close(is);
        }
    }


}
